<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <p>
    1
  </p>
  <p>
    2
  </p>
  <p>
    3
  </p>
  <p>
    4
  </p>
  <input id="input" />
  <script>
    // 节流：throttle
    
    function doSomething(){
      // getMilliseconds获取毫秒数
      console.log((new Date()).toLocaleTimeString(), (new Date()).getMilliseconds(),'假装发ajax', input.value)
    }

    // 输入一个函数及要求做节流处理时间频率
    // 返回一个具备节流效果的函数
    function throttle(fn, t) {
      let timerId = null
      function throttleDoSomething(){
        if(timerId) {
          return 
        }
        timerId = setTimeout(() => {
          fn()
          timerId = null
        },t)
      }
      return throttleDoSomething
    }
    // 对于  throttleDoSomething ，无论你用多高频率去调用它，
    // 它最多只为以500ms调用一次的频率来调用doSomething
    const throttleDoSomething = throttle(doSomething, 500)
    // let timerId = null
    // function throttleDoSomething(){
    //   if(timerId) {
    //     return 
    //   }
    //   timerId = setTimeout(() => {
    //     doSomething()
    //     timerId = null
    //   },500)
    // }

    document.getElementById('input').addEventListener('input', () => {
      console.log('文本框内容变化')
      // doSomething()
      throttleDoSomething()
    }) 
    
    // window.addEventListener('scroll',() => {
    //   console.log('滚动条')
    //   doSomething()
    // })
    // window.addEventListener('resize',() => {
    //   console.log('窗口缩放')
    //   doSomething()
    // })
    // document.addEventListener('mousemove',() => {
    //   console.log('鼠标移动')
    //   doSomething()
    // })

    // const _doSomething = debounceBuilder(doSomething,1000)
    // document.getElementById('div').onmousemove = function () {

    // }



    // let timer = null
    // function debounce_doSomething () {
    //   clearTimeout(timer)
    //   timer = setTimeout(() => {
    //     doSomething()
    //   }, 1000)
    // }

    

    // let timer = null
    // function throttle() {
    //   if(timer) {
    //     return
    //   }
    //   timer = setTimeout(() => {
    //     doSomething()
    //     timer2 = null
    //   }, 1000)
    // }

  </script>
</body>
</html>